import { PageContainer, Text, View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { useBoolean } from "ahooks";

import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import Money from "@/components/app/Money";
import ByIcon from "@/components/ui/ByIcon";
import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import Sticky from "@/components/app/Sticky";
import TabsTag from "@/components/app/TabsTag";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import PopupStagePayment from "./components/PopupStagePayment";

import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";
import ApiFinance from "@/api/finance";

import { objectToQueryString } from "@/utils";

// import { ReceiptBill } from "@/types/finance";

const tabItems = [
  { label: "待付款", value: 1 },
  { label: "已收款", value: 2 },
];

type ReceiptBill = {
  /**
   * 已付
   */
  paidAmount: number;
  /**
   * 应付
   */
  payableAmount: number;
  summary: string;
  /**
   * 模板明细ID
   */
  templateDetailId: number;
  /**
   * 模板ID
   */
  templateId: number;
  /**
   * 剩余未付
   */
  unpaidAmount: number;

  bills: ReceiptBillItem[];
};

/**
 * ReceiptBillItem
 */
interface ReceiptBillItem {
  billNo: string;
  billType: number;
  createDate: string;
  createUserId: number;
  createUserName: string;
  payDateTime: string;
  paymentMode: string;
  realAmount: number;
  receiptBillId: number;
  remark: string;
  /**
   * 1.待付款， 2.已付款
   */
  status: number;
  totalAmount: number;
  [property: string]: any;
}

const FinanceTaskItem = ({
  intentCustomerId,
  source,
}: {
  intentCustomerId: number;
  source: ReceiptBill;
}) => {
  const navigate = (item) => {
    const { status, receiptBillId } = item;

    if (status === 1) {
      Taro.navigateTo({
        url: `/packageProject/pages/finance/qrcode?${objectToQueryString({
          receiptBillId,
          intentCustomerId,
        })}`,
        success(res) {
          res.eventChannel.emit("acceptReceiptBill", source);
        },
      });
    }
  };

  return (
    <Card className="mb-3">
      <ByRow content="between">
        <ByText bold size="lg">
          {source.summary}
        </ByText>

        <View>
          <ByText size="sm" type="third">
            应收款:
          </ByText>
          <Money bold size="sm" value={source.payableAmount} />
        </View>
      </ByRow>

      <ByRow content="between" className="mt-1">
        <ByCol span={6}>
          <ByText size="sm" type="third">
            已收款:
          </ByText>
          <Money bold size="sm" value={source.paidAmount} />
        </ByCol>
        <ByCol span={6}>
          <ByText size="sm" type="third">
            剩余应收：
          </ByText>
          <Money bold size="sm" value={source.unpaidAmount} />
        </ByCol>
      </ByRow>

      {source.bills.map((item) => (
        <ByRow
          align="center"
          content="between"
          key={item.billNo}
          className="py-2"
          onClick={() => navigate(item)}
        >
          <Money
            value={item.totalAmount}
            type={item.status === 2 ? "success" : "primary"}
          />

          {item.status === 2 ? (
            <ByText type="third" size="sm">
              {item.payDateTime}
            </ByText>
          ) : (
            <ByIcon
              size={46}
              name="QRCode"
              className="shadow-black-1 text-primary"
            />
          )}
        </ByRow>
      ))}
    </Card>
  );
};

export default () => {
  const { params } = useRouter<{ intentCustomerId: `${number}` }>();

  const intentCustomerId = Number(params.intentCustomerId);

  const [visible, { setTrue, setFalse }] = useBoolean();
  const [active, setActive] = useState(1);

  const { data } = useFetch<{
    /**
     * 客户地址
     */
    customerAddress: string;
    /**
     * 客户名称
     */
    customerName: string;
    /**
     * 客户编号
     */
    customerNo: string;
    /**
     * 已付款总额
     */
    paidAmount: number;
    /**
     * 已付款次数
     */
    paidCount: number;
    /**
     * 待付款金额
     */
    pendingAmount: number;
    /**
     * 合同总金额
     */
    totalAmount: number;
  }>(ApiFinance.paymentSummary, {
    defaultParams: [{ intentCustomerId }],
  });

  const { loading, list, refresh, resetToFirst } = useList<ReceiptBill>(
    ApiFinance.getReceiptList,
    { manual: true }
  );

  useEffect(() => {
    resetToFirst({ intentCustomerId });
  }, [active]);

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <View className="p-3 text-center">
            <ByButton className="w-2/3" size="large" onClick={setTrue}>
              发起收款
            </ByButton>
          </View>
        }
      >
        <View className="p-3">
          <Card>
            <ByRow content="between">
              <Text>{data?.customerName}</Text>
              <Text className="text-sm text-third">
                {data?.customerAddress}
              </Text>
            </ByRow>

            <View className="my-3 text-sm text-second">
              用户已付款{data?.paidCount}次，付款总额
              <Money value={data?.paidAmount} />
            </View>

            <View className="font-bold">
              <Text>待付款：</Text>
              <ByText bold type="primary">
                <Money value={data?.pendingAmount} />
              </ByText>
              /
              <Money value={data?.totalAmount} />
            </View>
          </Card>

          {/* <Sticky position="top" className="z-10 py-3 my-2">
            <TabsTag
              mode="auto"
              items={tabItems}
              active={active}
              onChange={setActive}
            />
          </Sticky> */}

          <ListView loading={loading} isEmpty={list.length == 0}>
            {list.map((item) => (
              <FinanceTaskItem
                source={item}
                key={item.templateDetailId}
                intentCustomerId={intentCustomerId}
              />
            ))}
          </ListView>
        </View>
      </Page>

      <PageContainer round show={visible} onLeave={setFalse}>
        <PopupStagePayment
          intentCustomerId={+params.intentCustomerId}
          onCancel={setFalse}
          onConfirm={() => (setFalse(), refresh())}
        />
      </PageContainer>
    </>
  );
};
